<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useForm, useFormRules } from '@/hooks/common/form';
import { fetchChangePassword } from '@/service/api/user';
import { useAuthStore } from '@/store/modules/auth';
defineOptions({ name: 'ChangePasswordDialog' });

const props = defineProps<{
  visible: boolean;
}>();

const emit = defineEmits<{
  'update:visible': [value: boolean];
  'success': [];
}>();

const authStore = useAuthStore();

const { formRef, validate, restoreValidation } = useForm();

interface FormModel {
  oldPassword: string;
  newPassword: string;
  confirmPassword: string;
}

const model = ref<FormModel>({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

type RuleRecord = Partial<Record<keyof FormModel, App.Global.FormRule[]>>;

const rules = computed<RuleRecord>(() => {
  const { formRules, createConfirmPwdRule } = useFormRules();

  return {
    oldPassword: [{
      required: true,
      message: '请输入旧密码',
      trigger: 'change'
    }],
    newPassword: formRules.pwd,
    confirmPassword: createConfirmPwdRule(model.value.newPassword)
  };
});

// 监听弹框显示状态，清除验证错误
watch(() => props.visible, (newVisible) => {
  if (newVisible) {
    // 弹框打开时清除验证错误
    formRef.value?.clearValidate();
  }
});

function handleClose() {
  emit('update:visible', false);
  // 重置表单
  model.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  };
}

async function handleSubmit() {
  await validate();
  
  try {
    const { data, error } = await fetchChangePassword({
      oldPwd: model.value.oldPassword,
      newPwd: model.value.newPassword,
      userCode: authStore.userInfo.code
    });
    
    if (!error) {
      window.$message?.success('密码修改成功');
      emit('success');
      handleClose();
    }
  } catch (error) {
    console.error('修改密码失败:', error);
  }
}
</script>

<template>
  <ElDialog
    :model-value="visible"
    title="修改密码"
    width="600px"
    :close-on-click-modal="false"
    :modal="true"
    :append-to-body="true"
    @update:model-value="(value) => emit('update:visible', value)"
    @close="handleClose"
  >
    <ElForm
      ref="formRef"
      :model="model"
      :rules="rules"
      label-width="100px"
      @keyup.enter="handleSubmit"
    >
      <ElFormItem label="旧密码" prop="oldPassword">
        <ElInput
          v-model="model.oldPassword"
          type="password"
          show-password-on="click"
          placeholder="请输入旧密码"
        />
      </ElFormItem>
      <ElFormItem label="新密码" prop="newPassword">
        <ElInput
          v-model="model.newPassword"
          type="password"
          show-password-on="click"
          placeholder="请输入新密码"
        />
      </ElFormItem>
      <ElFormItem label="确认密码" prop="confirmPassword">
        <ElInput
          v-model="model.confirmPassword"
          type="password"
          show-password-on="click"
          placeholder="请再次输入新密码"
        />
      </ElFormItem>
    </ElForm>
    
    <template #footer>
      <ElSpace>
        <ElButton @click="handleClose">取消</ElButton>
        <ElButton type="primary" @click="handleSubmit">确认</ElButton>
      </ElSpace>
    </template>
  </ElDialog>
</template>

<style scoped>
:deep(.el-overlay) {
  z-index: 9999 !important;
}

:deep(.el-dialog) {
  z-index: 10000 !important;
}

:deep(.el-dialog__wrapper) {
  z-index: 9999 !important;
}
</style> 